package com.lw.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;

/**
 * 加密工具类
 * @author 刘伟
 * 
 */
public class Encrypt {
	private static final Logger LOG = LoggerFactory.getLogger(Encrypt.class);
	private static final String MD5 = "md5";
	private static final String SHA_1 = "sha-1";
	/* 加密的盐字符串  */
	public final static String ENCRYPT_SALT = "ssm";
	
	//the number of times the argument hashed for attack resiliency.
	public final static int SALT_NUMS = 10;

	/**
	 * 加密
	 * 
	 * @param inputText
	 * @return
	 */
	public static String e(String inputText) {
		return md5(inputText);
	}

	/**
	 * 二次加密，应该破解不了了吧？
	 * 
	 * @param inputText
	 * @return
	 */
	public static String md5AndSha(String inputText) {
		return sha(md5(inputText));
	}

	/**
	 * md5加密
	 * 
	 * @param inputText
	 * @return
	 */
	public static String md5(String inputText) {
		return encrypt(inputText, MD5);
	}

	/**
	 * sha加密
	 * 
	 * @param inputText
	 * @return
	 */
	public static String sha(String inputText) {
		return encrypt(inputText, SHA_1);
	}

	/**
	 * md5或者sha-1加密
	 * 
	 * @param inputText
	 *            要加密的内容
	 * @param algorithmName
	 *            加密算法名称：md5或者sha-1，不区分大小写
	 * @return
	 */
	private static String encrypt(String inputText, String algorithmName) {
		if (StringUtils.isEmpty(inputText)) {
			throw new IllegalArgumentException("请输入要加密的内容");
		}
		if (StringUtils.isEmpty(algorithmName)) {
			algorithmName = MD5;
		}
		String encryptText = null;
		try {
			MessageDigest m = MessageDigest.getInstance(algorithmName);
			m.update(inputText.getBytes("UTF8"));
			byte s[] = m.digest();
			return hex(s);
		} catch (NoSuchAlgorithmException e) {
			LOG.error("", e);
		} catch (UnsupportedEncodingException e) {
			LOG.error("", e);
		}
		return encryptText;
	}

	/**
	 * 返回十六进制字符串
	 * 
	 * @param arr
	 * @return
	 */
	private static String hex(byte[] arr) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < arr.length; ++i) {
			sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3));
		}
		return sb.toString();
	}

	/**
	 * sha256Hash加密
	 * 
	 * @param password
	 * @return
	 */
	public static String sha256Hash(String password) {
		return new Sha256Hash(password, ENCRYPT_SALT, SALT_NUMS).toBase64();
	}

}
